<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace Model\CourseCategoryBundle\Model;

use Base\BaseModel;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Model\CourseCategoryBundle\Setting\CourseCategorySetting;
use Symfony\Component\HttpFoundation\Request;

class CourseCategoryModel extends BaseModel{


    /*
     * 列表基本设置【通用模块必须】
     */
    public function listSettingDefault()
    {
        $settings = new CourseCategorySetting($this->getDoctrine());
        return $settings->listConfig();
    }

    //获取所有分类
    public function getAllCourseCategory(){
        $qb = $this->getQueryBuilder();
        $qb->select("*")
        ->from("CourseCategory");
        return $qb->execute()->fetchAll();
    }

    //获取所有分类并构建分类树
    public function getAllCourseCategoryTree()
    {
        $categories = $this->getAllCourseCategory();
        $CourseCategoryTree = $this->buildeCatTreeArray($categories);
        $data = array();
        foreach ($CourseCategoryTree as $class) {
            $prefix = "";
            if ($class["level"] > 0) {
                $prefix .="├";
                for ($i=0;$i<$class["level"];$i++ ) {
                    $prefix .="─";
                }
            }
            $data[] = array(
                "id"=>$class["id"],
                "name"=>$prefix.$class["name"],
                "catName"=>$class["name"],
                "parent"=>$class["parent"],
                "level"=>$class["level"],
            );
        }
        return $data;
    }

    //获取第一层分类
    public function getRootCourseCategory ()
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")
            ->where("parent = ?")
            ->setParameter(0,"0")
            ->from("CourseCategory")
            ->orderBy("orders","asc");
        return $qb->execute()->fetchAll();
    }

    public function getSonsInNextLevel($parent)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")
            ->where("parent = ?")
            ->setParameter(0,$parent)
            ->from("CourseCategory")
            ->orderBy("orders","asc");
        return $qb->execute()->fetchAll();
    }



    public function getOne($id)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")
            ->where("id = ?")
            ->setParameter(0,$id)
            ->from("CourseCategory");
        return $qb->execute()->fetch();
    }


    public function getAllCourseCategoryForWebIndex()
    {
        $root = $this->getRootCourseCategory();
        $collections = array();
        $collections[0] = $root;
        foreach ($root as $category) {
            $sons = $this->getSonsInNextLevel($category["id"]);
            $collections[$category["id"]] = $sons;
            foreach ($sons as $son) {
                $collections[$son["id"]] = $this->getSonsInNextLevel($son["id"]);
            }
        }
        return $collections;
    }

    public function getAllSonIds($rootId,&$ids)
    {
        $ids[] = (int)$rootId;
        $sons = $this->getSonsInNextLevel($rootId);
        if (!empty($sons)) {
            foreach ($sons as $nextRoot) {
                $this->getAllSonIds($nextRoot["id"],$ids);
            }
        }
    }

    public function update( $id , $array )
    {
        $qb = $this->getQueryBuilder();
        $qb->update("CourseCategory");
        foreach ($array as $key => $val) {
            $qb->set($key,":$key")->setParameter("$key",$val);
        }
        $qb->where("id = :id")->setParameter("id",$id);
        $qb->execute();
    }

    public function setIsRoot($id)
    {
        $data = array(
            "level"  => 0,
            "parent"  => 0,
            "link"   => "[$id]"
        );
        $this->update($id,$data);
    }

    public function getTopParent($id)
    {
        //异常情况分两种
        //1.关系链不完整从中间断开
        //2.存在闭合的循环
        $tmpArray4ParentIds = array();
        $CourseCategory = $this->getOne($id);
        while ( $CourseCategory["parent"] != 0 ) {
            if ( in_array($CourseCategory["parent"],$tmpArray4ParentIds)) {
                $this->setIsRoot($CourseCategory["parent"]);
                return $CourseCategory["id"];
            }
            $tmpArray4ParentIds[] = $CourseCategory["parent"];
            $parent = $CourseCategory;
            $CourseCategory = $this->getOne($CourseCategory["parent"]);
            if (!$CourseCategory) {
                //找不到该分类,就从断开的位置设置成root分类
                $this->setIsRoot($parent["id"]);
                return $parent["id"];
            }
        }
       return $CourseCategory["id"];
    }

    public function updateAll()
    {
        //梳理之前更新level 至-1
        $qb = $this->getQueryBuilder();
        $qb->update("CourseCategory");
        $qb->set("level",":level")->setParameter("level",-1);
        $qb->set("link",":link")->setParameter("link","");
        $qb->execute();

        //从根目录开始逐层梳理
        $root = $this->getRootCourseCategory();
        foreach ( $root as $category ) {
            if (
                $category["level"] != 0
                || $category["link"] != ""
            ) {
                $this->setIsRoot($category["id"]);
            }
        }
        $this->updateLinkAndLevel();
        do{

            $unDo = $this->getBadCategory();
            foreach ($unDo as $cat) {
                $this->getTopParent($cat["id"]);
            }
            $this->updateLinkAndLevel();
        }while(!empty($unDo));
            return true;
    }

    public function updateLinkAndLevel()
    {
        $root = $this->getRootCourseCategory();
        $i = 0;
        do{
            $level = $i;
            $sonArray = array();
            $hasNextLevel = 0;
            foreach ( $root as $category ) {

                $data = array(
                    "level"  => $level
                );
                if (!$category["link"]) {
                    $parent = $this->getOne($category["parent"]);
                    $data["link"] = $parent["link"]."[".$category["id"]."]";
                }
                $this->update($category["id"],$data);
                $sons = $this->getSonsInNextLevel($category["id"]);
                foreach ($sons as $son) {
                    $data = array(
                        "level"  => $level + 1,
                        "link"   => $category["link"]."[".$son["id"]."]"
                    );
                    $this->update($son["id"],$data);
                    $nextSons = $this->getSonsInNextLevel($son["id"]);
                    if (!empty($nextSons)) {
                        $hasNextLevel = 1;
                        break;
                    }
                }
                $sonArray = array_merge($sonArray,$sons);
            }
            $i++;
            $root = $sonArray;
        }while($hasNextLevel);
    }

    public function getBadCategory()
    {
        //梳理完成，检查是否有遗漏
        $qb = $this->getQueryBuilder();
        $qb->select("*")
            ->where("level = ?")
            ->setParameter(0,-1)
            ->from("CourseCategory");
        $unDo = $qb->execute()->fetchAll();
        return $unDo;
    }

    public function getAllGroupByParent()
    {
        $allCat = $this->getAllCourseCategory();
        $groups = array();
        foreach ( $allCat as $cat ) {
            $groups[$cat["parent"]][] = array_values($cat);
        }
        return $groups;
    }


}